﻿(function ($) {

    $.fn.longclick = function (element, callback) {

        var eventType = {
            mousedown: 'ontouchstart' in window ? 'touchstart' : 'mousedown',
            mouseup: 'ontouchend' in window ? 'touchend' : 'mouseup'
        };

        var mousepress_time = 700;


        var cancelLong = function () {
            clearTimeout($(this).data("checkdown"));
        };

        var startFuncion= function (e) {
            var $this = $(this);
            $(this).data("checkdown", setTimeout(function () {
                callback($this,e);
            }, mousepress_time));
        };

        $(this).on("mousedown", element, startFuncion)
            .on("mouseup", element, cancelLong)
            .on("mouseout", element, cancelLong)
            .on("mousemove", element, cancelLong);
    };

    $.fn.customTable = function (options) {
        // Script 1
        var opt = {
            "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": [0]
            }],
            "aaSorting": [
                [1, 'asc']
            ],
            "oLanguage": {
                "sSearch": translate("_search") + ": ",
                "sLengthMenu": translate("_display") + " " + "_MENU_" + " " +translate("_recordsPerPage"),
                "sZeroRecords": translate("_nothingFoundSorry"),
                "sInfo": translate("_showingPage") + " " + "_START_" + " " + translate("_of") + " " + "_END_",
                "sInfoEmpty": translate("_noRecordsAvailable"),
                "sInfoFiltered": translate("_filteredFrom")+" "+ "_MAX_" +" "+translate("_totalRecords")
            }
        };
        $.extend(opt, options);

        function fnFormatDetails(oTable, nTr) {
            var aData = oTable.fnGetData(nTr);
            var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
            sOut += '<tr><td>Email:</td><td>' + aData[1] + ' ' + aData[4] + '</td></tr>';
            //sOut += '<tr><td>Link to source:</td><td>Could provide a link here</td></tr>';
            //sOut += '<tr><td>Extra info:</td><td>And any further details here (images etc)</td></tr>';
            sOut += '</table>';
            return sOut;
        }


        /*  Insert a 'details' column to the table  */
        var nCloneTh = document.createElement('th');
        var nCloneTd = document.createElement('td');
        nCloneTd.innerHTML = '<i style="color: #C75757" class="fa fa-plus-square-o"></i>';
        nCloneTd.className = "center";

        $(this).find('thead tr').each(function () {
            this.insertBefore(nCloneTh, this.childNodes[0]);
        });

        $(this).find('tbody tr').each(function () {
            this.insertBefore(nCloneTd.cloneNode(true), this.childNodes[0]);
        });

        /*  Initialse DataTables, with no sorting on the 'details' column  */
        var oTable = $(this).dataTable(opt);

        /*  Add event listener for opening and closing details  */
        oTable.find('tbody td i').on('click', function () {
            //$(document).on('click', '#table2 tbody td i', function () {
            var nTr = $(this).parents('tr')[0];
            if (oTable.fnIsOpen(nTr)) {
                /* This row is already open - close it */
                $(this).removeClass().addClass('fa fa-plus-square-o');
                oTable.fnClose(nTr);
            } else {
                /* Open this row */
                $(this).removeClass().addClass('fa fa-minus-square-o');
                oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr), 'details');
            }
        });
        // toDo: funciones de ajuste?
    };
    
    /*$.fn.customTable = function (element, options) {

        var opt = {
            "sPaginationType": "full_numbers",
            "oLanguage": {
                "sSearch": "<span>" + translate("search") + ":</span> ",
                "sInfo": "" + translate("showing") + " <span>_START_</span> " + translate("to") + " <span>_END_</span> " + translate("of") + " <span>_TOTAL_</span> " + translate("entries") ,
                "sLengthMenu": "_MENU_ <span>" + translate("entries_per_page") + "</span>"
            },
            'sDom': "lfrtip"
        };

        $.extend(opt, options);

        if ($(this).hasClass("dataTable-noheader")) {
            opt.bFilter = false;
            opt.bLengthChange = false;
        }
        if ($(this).hasClass("dataTable-nofooter")) {
            opt.bInfo = false;
            opt.bPaginate = false;
        }
        if ($(this).hasClass("dataTable-nosort")) {
            var column = $(this).attr('data-nosort');
            column = column.split(',');
            for (var i = 0; i < column.length; i++) {
                column[i] = parseInt(column[i]);
            };
            opt.aoColumnDefs = [{
                'bSortable': false,
                'aTargets': column
            }];
        }
        if ($(this).hasClass("dataTable-scroll-x")) {
            opt.sScrollX = "100%";
            opt.bScrollCollapse = true;
            $(window).resize(function () {
                oTable.fnAdjustColumnSizing();
            });
        }
        if ($(this).hasClass("dataTable-scroll-y")) {
            opt.sScrollY = "300px";
            opt.bPaginate = false;
            opt.bScrollCollapse = true;
            $(window).resize(function () {
                oTable.fnAdjustColumnSizing();
            });
        }
        if ($(this).hasClass("dataTable-reorder")) {
            opt.sDom = "R" + opt.sDom;
        }
        if ($(this).hasClass("dataTable-colvis")) {
            opt.sDom = "C" + opt.sDom;
            opt.oColVis = {
                "buttonText": "Change columns <i class='icon-angle-down'></i>"
            };
        }
        if ($(this).hasClass("dataTable-grouping") && $(this).attr("data-grouping") == "expandable") {
            opt.bLengthChange = false;
            opt.bPaginate = false;
        }

        var oTable = $(this).dataTable(opt);

        $(this).css("width", '100%');
        $('.dataTables_filter input').attr("placeholder", translate("search_here")+"...");
        $(".dataTables_length select").wrap("<div class='input-mini'></div>").chosen({
            disable_search_threshold: 9999999
        });
        // Options para el header de la tabla
        $('<div class="actions data-table-options">').insertAfter(".dataTables_length");

        $("#check_all").click(function (e) {
            $('input', oTable.fnGetNodes()).prop('checked', this.checked);
        });
        if ($(this).hasClass("dataTable-fixedcolumn")) {
            new FixedColumns(oTable);
        }
        if ($(this).hasClass("dataTable-columnfilter")) {
            oTable.columnFilter({
                "sPlaceHolder": "head:after"
            });
        }
        if ($(this).hasClass("dataTable-grouping")) {
            var rowOpt = {};

            if ($(this).attr("data-grouping") == 'expandable') {
                rowOpt.bExpandableGrouping = true;
            }
            oTable.rowGrouping(rowOpt);
        }

        oTable.fnDraw();
        oTable.fnAdjustColumnSizing();
     
        return oTable;
        
    };*/

    $.fn.colorPicker = function (element, options) {
        var opt = {
            "className": "full-spectrum",
            "allowEmpty": true,
            "showInput": true,
            "showInitial": true,
            "showPalette": true,
            "showSelectionPalette": true,
            "maxPaletteSize": 10,
            "preferredFormat": "hex",
            "localStorageKey": "spectrum.demo",
            "chooseText": translate("_choose"),
            "cancelText": translate("_cancel"),
            "palette": [
                ["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)",
                "rgb(204, 204, 204)", "rgb(217, 217, 217)", "rgb(255, 255, 255)"],
                ["rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)",
                "rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"],
                ["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
                "rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
                "rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
                "rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
                "rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
                "rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
                "rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
                "rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
                "rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
                "rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)"]
            ]
        };

        $.extend(opt, options);

        var oPicker = $(this).spectrum(opt);
    }

    $.uuid = function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    };

    $.fn.captureImage = function ( callback) {


        $(this).find("svg").each(function (index, item) {

            //replace svg for images
            var canvas = document.createElement("canvas");
            canvg(canvas, $(item).parent().html());
            var img_url = canvas.toDataURL('image/png');
            var tt = 0, ll = 0;
            if ($(item).position()) {
                if ($(item).position().top)
                    tt = $(item).position().top;
                if ($(item).position().left)
                    ll = $(item).position().left;
            }
            $(item).parent().append("<img class='tmpsvg' style='position: absolute;top: "+tt+"px;left: "+ll+"px;' />");
            $(item).parent().find("img.tmpsvg").attr("src", img_url);

        });

        //take screenshot
        var _this = this;

        html2canvas(_this, {
            useCORS: true,
            allowTaint: true,
            onrendered: function (canvas) {
                
                var img = canvas.toDataURL("image/png");
                var output = img.replace(/^data:image\/(png|jpg);base64,/, "");

                //remove images and show svg again
                $(_this).find("img.tmpsvg").remove();
                

                callback(output);

            }
        });        

    };

    $.validator.addMethod("customvalue", function (value, element, param) {
        return this.optional(element) || parseFloat(value) === param;
    }, "Value must be equal to " + "{0}");

    // COMENTADO: NO tengo context menu agregado por ahora. ES PARA EL MAPA
    //$.contextMenu.types.icon_text = function (item, opt, root) {
    //    // this === item.$node
    //    $('<i class="'+ item.iconClass +'"></i><span>'+item.name+'</span>').appendTo(this);
        
    //};


   
})(jQuery);